import math
import matplotlib.pyplot as plt
import numpy as np

import numpy as np

def project_point_on_line_segment(point, line_start, line_end):
    # Step 1: Compute the direction vector `v` of the line segment
    v = line_end - line_start

    # Step 2: Compute the vector `w` between the point and the line start
    w = point - line_start

    # Step 3: Calculate the projection of w onto v
    mu = np.dot(w, v) / np.dot(v, v)

    # Step 4: Clamp the value of mu between 0 and 1
    mu = np.clip(mu, 0, 1)

    print(mu)

    # Step 5: Calculate the projection point
    projection = line_start + mu*v

    return projection


# 设置中文字体支持（可选）
plt.rcParams['font.sans-serif'] = ['SimHei']  # 用来正常显示中文标签
plt.rcParams['axes.unicode_minus'] = False  # 用来正常显示负号

line_start = np.array([1, 1])
line_end = np.array([20, 45])
point = np.array([5, 40])

# 创建图形
plt.figure(figsize=(8, 6))  # 设置图形大小

# 绘制折线图
plt.plot((line_start[0],line_end[0]), (line_start[1],line_end[1]), label='线性增长', color='blue', linestyle='-', marker='o')

plt.plot(point[0],point[1],'ro')

result = project_point_on_line_segment(point,line_start,line_end)
print(f'投影点坐标{result}')

plt.plot(result[0],result[1],'ro')

# plt.arrow(1,3,3-1,6-3,fc='blue',ec='red',head_width=0.2,head_length=0.2)

# 添加标题和标签
plt.title('简单折线图示例')
plt.xlabel('X轴')
plt.ylabel('Y轴')

# 添加图例
plt.legend()
# 坐标轴一致
plt.axis('equal')
# 显示网格
plt.grid(True, linestyle='--', alpha=0.5)

# 显示图形
plt.show()